<template>
	<!-- multiple -->
	<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" 
		:maxCount="1"></u-upload>
</template>

<script>
	export default {
		props: {
			value: {
				type: Array,
				default: () => {
					return []
				}
			}
		},
		data() {
			return {
				fileList1_old: [],
			};
		},
		computed: {
			fileList1: {
				get() {
					return this.value
				},
				set(val) {
					this.$emit('input', val)
				}
			}
		},
		watch: {
			fileList1: {
				handler(newVal) {
					this.$emit('success', newVal)
				},
				deep: true
			}
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				console.log('event.name', event.name)
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result.url,
							path: result.path,
							pkid: result.pkid,
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: "https://lyw.cdbytech.top:3017/bytech/file/upload", // 仅为示例，非真实的接口地址
						filePath: url,
						name: "file",
						formData: {
							user: "test",
						},
						success: (res) => {
							const _data = JSON.parse(res.data || '{}')
							console.log('返回结果', _data)
							const fileInfo = _data.data?.files[0] || {
								name: '',
								pkid: '',
								size: ''
							}
							const _name = fileInfo.name || ''
							let _url = ''
							let _path = ''
							if (_name) {
								_url = `https://lyw.cdbytech.top:3017/images/${_name}`
								_path = `/images/${_name}`
							}
							setTimeout(() => {
								resolve({
									url: _url,
									path: _path,
									pkid: fileInfo.pkid
								});
							}, 100);
						},
					});
				});
			},
		},
	};
</script>